import React, { useState, useRef, useEffect } from "react";
import _ from 'lodash'
import { Form, Input, Select, Space, Button, DatePicker, Tabs } from "antd";
import { SearchOutlined, ExclamationCircleFilled } from "@ant-design/icons";
import { apiGetCalssify, apiGetCommodityList, apiProductInfoApprove, apiProductInfoRejected } from '@/request/commodity'
import { getDateTime3 } from '@/utils/getDate'
import ThePagination from "@/components/ThePagination";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheDialog from "@/components/TheDialog";
import TheImage from "@/components/TheImage";
import "../style/style.less";

const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { TextArea } = Input;

const SearchHeader = ({ getValue }) => {
  const formRef = useRef()
  const [options, setOptions] = useState([])
  useEffect(async () => {
    let res = await apiGetCalssify()
    if (res.code === 0 && res.data) {
      let options = res.data.map(v => {
        return {
          value: v.productClassifyId,
          label: v.productClassifyName
        }
      })
      setOptions(options)
    }
  }, [])
  const onFinish = (values) => {
    if (values.time && values.time.length) {
      values.createTimeStart = getDateTime3(values.time[0])
      values.createTimeEnd = getDateTime3(values.time[1])
    }
    delete (values.time)
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      productName: '',
      productId: '',
      productStatus: '',
      classifyId: null,
      time: []
    })
    getValue({})
  };
  return (
    <Form layout={'inline'} ref={formRef} onFinish={onFinish}>
      <Form.Item name={"productName"}>
        <Input style={{ width: 140 }} suffix={<SearchOutlined />} placeholder={"商品名称"} />
      </Form.Item>
      <Form.Item name={"productId"}>
        <Input style={{ width: 140 }} suffix={<SearchOutlined />} placeholder={"商品ID"} />
      </Form.Item>
      {/* <Form.Item name={"productStatus"} label="上架状态">
        <Select
          style={{ width: 140 }}
          options={[{ value: 'Y', label: '上架' }, { value: 'N', label: '下架' }, { value: 'G', label: '管理员关闭' }]}
          placeholder={"上架状态"}
        />
      </Form.Item> */}
      <Form.Item name={"classifyId"} label="所属类目">
        <Select
          style={{ width: 140 }}
          options={options}
          placeholder={"所属类目"}
        />
      </Form.Item>
      <Form.Item name={"time"} label="申请时间">
        <RangePicker />
      </Form.Item>
      <Form.Item>
        <Space size="small" style={{ marginLeft: 10 }}>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          <Button onClick={reset}>重置</Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

class Examine extends React.Component {
  state = {
    columnsS: [
      {
        title: "商品ID",
        dataIndex: "productId",
        key: "productId",
      },
      {
        title: "商品名称",
        dataIndex: "productName",
        key: "productName",
      },
      {
        title: "商品图片",
        dataIndex: "productShowImages",
        key: "productShowImages",
        render: (text, record) => {
          return <TheImage src={record.productShowImages} width={80} height={80} />
        }
      },
      {
        title: "商品分类",
        dataIndex: "productClassifyName",
        key: "productClassifyName",
      },
      {
        title: "商品原价",
        dataIndex: "originalPrice",
        key: "originalPrice",
        render: (text, record) => {
          return <React.$Price price={record.originalPrice || 0} />
        }
      },
      {
        title: "商品现价",
        dataIndex: "currentPrice",
        key: "currentPrice",
        render: (text, record) => {
          return <React.$Price price={record.currentPrice || 0} />
        }
      },
      {
        title: "所属商家",
        dataIndex: "storeName",
        key: "storeName",
      },
      {
        title: "审核状态",
        render: () => {
          return <span>待审核</span>
        }
      },
      {
        title: "申请时间",
        dataIndex: "createTime",
        key: "createTime",
      },
      {
        title: "上次操作时间",
        dataIndex: "lastUpdateTime",
        key: "lastUpdateTime",
        render: (text, record) => {
          return record.lastUpdateTime ? record.lastUpdateTime : "/"
        }
      },
      {
        title: "操作人",
        dataIndex: "userName",
        key: "userName",
        render: (text, record) => {
          return record.userName ? record.userName : "/"
        }
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              <TheButton haspermi={['commodity:details']} onClick={() => this.props.history.push(`/commodity/list/detail/${render.productId}`)}>商品详情</TheButton>
              <TheButton haspermi={['commodity:pass']} onClick={() => this.cancelConfirm(render.productId)}>通过</TheButton>
              <TheButton haspermi={['commodity:rejected']} onClick={() => this.setState({ visible: true, rejectedProductId: render.productId ,textArea:'' })}>
                驳回
              </TheButton>
            </div>
          );
        },
      },
    ],
    dataS: [],
    columnsB: [
      {
        title: "商品ID",
        dataIndex: "productId",
        key: "productId",
      },
      {
        title: "商品名称",
        dataIndex: "productName",
        key: "productName",
      },
      {
        title: "商品图片",
        dataIndex: "productShowImages",
        key: "productShowImages",
        render: (text, record) => {
          return <TheImage src={record.productShowImages} width={80} height={80} />
        }
      },
      {
        title: "商品分类",
        dataIndex: "productClassifyName",
        key: "productClassifyName",
      },
      {
        title: "商品原价",
        dataIndex: "originalPrice",
        key: "originalPrice",
        render: (text, record) => {
          return <React.$Price price={record.originalPrice || 0} />
        }
      },
      {
        title: "商品现价",
        dataIndex: "currentPrice",
        key: "currentPrice",
        render: (text, record) => {
          return <React.$Price price={record.currentPrice || 0} />
        }
      },
      {
        title: "所属商家",
        dataIndex: "storeName",
        key: "storeName",
      },
      {
        title: "审核状态",
        render: () => {
          return <span>未通过</span>
        }
      },
      {
        title: "审核时间",
        dataIndex: "updateTime",
        key: "updateTime",
      },
      {
        title: "原因",
        dataIndex: "dismissReason",
        key: "dismissReason",
      },
    ],
    dataB: [],
    pageDataS: {
      pageNo: 1,
      pageSize: 10,
    },
    totalS: 0,
    pageDataB: {
      pageNo: 1,
      pageSize: 10,
    },
    totalB: 0,
    visible: false,
    reviewStatus: 'S',
    searchValue: {},
    rejectedProductId: '',
    textArea: ''
  };
  async componentDidMount() {
    await this.getData()
  }
  getData = async () => {
    const { reviewStatus, searchValue } = this.state
    let res = await apiGetCommodityList({ reviewStatus, ...searchValue, ...this.state[`pageData${reviewStatus}`] })
    if (res.data && res.code === 0) {
      this.setState({
        [`data${reviewStatus}`]: res.data,
        [`pageData${reviewStatus}`]: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        [`total${reviewStatus}`]: res.totalCount
      })
    }
  }
  tabChange = (key) => {
    this.setState({
      reviewStatus: key
    }, () => {
      this.getData()
    })
  };
  pageChangeS = (pageNo, pageSize) => {
    this.setState({
      pageDataS: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };
  pageChangeB = (pageNo, pageSize) => {
    this.setState({
      pageDataB: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };
  getValue = (value) => {
    this.setState({
      searchValue: value,
      pageDataS: {
        pageNo: 1,
        pageSize: 10
      },
      pageDataB: {
        pageNo: 1,
        pageSize: 10
      }
    }, () => {
      this.getData()
    })
  }
  TextChange(e) {
    this.setState({
      textArea: e.target.value
    })
  }
  cancelConfirm = (productId) => {
    React.$confirm({
      title: "您确认通过审核本条商品吗？",
      onOk: async () => {
        await apiProductInfoApprove({ productId })
          .then(
            (res) => {
              if (res.code === 0) {
                React.$message({
                  type: 'info',
                  content: '审核成功'
                })
              }
            }
          )
        this.getData()
      },
    });
  };
  handleCancel = () => {
    this.setState({ visible: false, rejectedProductId: '' });
  };
  handleOk = async () => {
    const dismissReason = this.state.textArea
    console.log(dismissReason);

    if (!dismissReason) {
      React.$message({
        type: 'error',
        content: '请填写驳回原因'
      })
      return
    } else {
      let res = await apiProductInfoRejected({ productId: this.state.rejectedProductId, dismissReason })
      if (res.code === 0) {
        this.setState({ visible: false, textArea: '' }, () => {
          React.$message({
            type: 'info',
            content: '驳回成功'
          })
          this.getData()
        });
      }
    }
  };
  render() {
    const {
      columnsS,
      columnsB,
      dataS,
      dataB,
      pageDataS,
      pageDataB,
      totalS,
      totalB,
      visible,
    } = this.state;
    return (
      <div className="p-layout-box commodity-examine">
        <div className="p-search-box">
          <SearchHeader getValue={this.getValue} />
        </div>
        <Tabs defaultActiveKey="S" onChange={this.tabChange}>
          <TabPane tab="待审核" key="S">
            <div className="p-layout-content-pagination">
              <TheTable
                scroll={{ x: "max-content", y: '63vh' }}
                columns={columnsS}
                dataSource={dataS}
              />
              <ThePagination
                pageNo={pageDataS.pageNo}
                pageSize={pageDataS.pageSize}
                total={totalS}
                pageChange={this.pageChangeS}
              />
            </div>
          </TabPane>
          <TabPane tab="未通过" key="B">
            <div className="p-layout-content-pagination">
              <TheTable
                scroll={{ x: "max-content", y: '63vh' }}
                columns={columnsB}
                dataSource={dataB}
              />
              <ThePagination
                pageNo={pageDataB.pageNo}
                pageSize={pageDataB.pageSize}
                total={totalB}
                pageChange={this.pageChangeB}
              />
            </div>
          </TabPane>
        </Tabs>
        <TheDialog
          title={
            <div>
              <ExclamationCircleFilled
                style={{ color: "#FAAD14", marginRight: 10 }}
              />
              输入驳回原因
            </div>
          }
          width={400}
          visible={visible}
          handleCancel={this.handleCancel}
          handleOk={this.handleOk}
        >
          <TextArea
            onChange={(e) => this.TextChange(e)}
            allowClear
            autoSize={{ minRows: 6, maxRows: 6 }}
            maxLength={50}
            showCount
          />
        </TheDialog>
      </div>
    );
  }
}

export default Examine;
